from odoo import fields, models, api
from odoo.exceptions import UserError


class RpThirdRouteCollect(models.Model):
    
    _name = "rp.third.route.collect"
    _description = "第三方邮路收集池"
    
    name = fields.Char("邮路名称")
    third_type = fields.Selection([("shippypro", "shippypro")], string="所属第三方")
    label = fields.Char("别称")
    route_id = fields.Char("邮路ID")
    route_logo = fields.Char("邮路logo")
    courier_id = fields.Many2one(string='承运商', comodel_name='rp.courier')
    update_time_stamp = fields.Integer("更新时间(时间戳)")
    active = fields.Boolean("有效", default=True)
    
    # 邮路同步
    def action_syn_route(self):
        pass
    
    def courier_deal(self, courier_name):
        """
        判断当前承运商是否存在，不存在则创建
        @param courier_name:承运商名称
        @return: 返回搜索到或者创建出的承运商的courier(rp.courier)
        """
        courier = self.env["rp.courier"].search(
            [("name", "=ilike", courier_name)], limit=1
        )
        if not courier:
            courier = self.env["rp.courier"].create(
                {"name": courier_name}
            )
        return courier
    
    @api.model
    def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
        if args is None:
            args = []
        args = args + ["|","|",('name', operator, name),('label', operator, name),('third_type', operator, name)]
        return self._search(args, limit=limit, access_rights_uid=name_get_uid)

    def name_get(self):
        result = []
        for r in self:
            text = '['+ r.third_type + ' ' + r.label + ']' + r.name
            result.append((r.id, text))
        return result
